/**
 * 项目名称：最简单的LED驱动程序
 * 单片机：STC8G1K08
 * 频率：11.0592Mhz
 * PCB:1603120A_Y3
 * 学习目标：写一个驱动程序依次点亮8个LED并达到跑马灯效果
   */

#include "stc8g.h" //加载此头文件以后不需要再加载reg51.h

#define LED_0 P35
#define LED_1 P34
#define LED_2 P10
#define LED_3 P11
#define LED_4 P16
#define LED_5 P17
#define LED_6 P54
#define LED_7 P55

unsigned char ledState; //led状态

//软件延时函数@11.0592MHz 本小节不必理会其原理
void Delay500ms() {
    unsigned char i, j, k;

    i = 29;
    j = 14;
    k = 54;
    do {
        do {
            while (--k);
        } while (--j);
    } while (--i);
}

//刷新LED状态
void led_update_display() {
    LED_0 = ledState & (0x01 << 0);
    LED_1 = ledState & (0x01 << 1);
    LED_2 = ledState & (0x01 << 2);
    LED_3 = ledState & (0x01 << 3);
    LED_4 = ledState & (0x01 << 4);
    LED_5 = ledState & (0x01 << 5);
    LED_6 = ledState & (0x01 << 6);
    LED_7 = ledState & (0x01 << 7);
}

//初始化IO
void pin_init() {
    P1M1 = 0x00;
    P1M0 = (0x01 << 7) | (0x01 << 6) | (0x01 << 1) | (0x01 << 0);

    P3M1 = 0x00;
    P3M0 = (0x01 << 5) | (0x01 << 4);

    P5M1 = 0x00;
    P5M0 = (0x01 << 5) | (0x01 << 4);
}

void main() {
    unsigned char i;
    pin_init();
    while(1) {
        ledState = 0x01;
        for(i = 0; i < 8; i++) {
            ledState <<= i;       //改变变量
            led_update_display(); //刷新同步
            Delay500ms();         //延时
        }
    }
}
